package com.fancy.learncenter.utils;

import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.drawable.Animatable;
import android.net.Uri;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.os.Environment;
import android.os.Environment;
import android.provider.Settings;
import android.support.annotation.Nullable;
import android.support.v4.BuildConfig;
import android.support.v4.content.FileProvider;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Base64;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;

import com.facebook.drawee.backends.pipeline.Fresco;
import com.facebook.drawee.controller.BaseControllerListener;
import com.facebook.drawee.controller.ControllerListener;
import com.facebook.drawee.interfaces.DraweeController;
import com.facebook.drawee.view.SimpleDraweeView;
import com.facebook.imagepipeline.image.ImageInfo;
import com.fancy.learncenter.activity.FancyActivityDetailActivity;
import com.fancy.learncenter.activity.GoodsDetailActivity;
import com.fancy.learncenter.activity.InviteDetailActivity;
import com.fancy.learncenter.activity.LifeVideoDetailActivity;
import com.fancy.learncenter.activity.PersonInfoActivity;
import com.fancy.learncenter.activity.ReleaseGraphicActivity;
import com.fancy.learncenter.activity.ReleaseHuoDongActivity;
import com.fancy.learncenter.activity.ReleasePeiXunActivity;
import com.fancy.learncenter.activity.ReleaseVideoActivity;
import com.fancy.learncenter.activity.ReleaseWenDaActivity;
import com.fancy.learncenter.activity.ReleaseXianZhiActivity;
import com.fancy.learncenter.activity.ReleaseZhiWeiActivity;
import com.fancy.learncenter.activity.ToothDetailsActivity;
import com.fancy.learncenter.activity.TrainApplyDetailActivity;
import com.fancy.learncenter.activity.TzDetailActivity;
import com.fancy.learncenter.activity.VideoDetailActivity;
import com.fancy.learncenter.bean.BaseDataBean;
import com.fancy.learncenter.bean.RongYunDataBean;
import com.fancy.learncenter.common.Constant;
import com.fancy.learncenter.common.MyApplication;
import com.fancy.learncenter.net.HttpMehtod;
import com.fancy.learncenter.net.IdeaObserver;
import com.jph.takephoto.compress.CompressConfig;
import com.jph.takephoto.model.CropOptions;
import com.umeng.analytics.MobclickAgent;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import io.rong.imkit.RongIM;
import io.rong.imlib.RongIMClient;
import io.rong.imlib.model.UserInfo;

/**
 * Created by Hyy on 2016/11/2.
 */
public class Utils {

    // 两次点击按钮之间的点击间隔不能少于1000毫秒
    private static final int MIN_CLICK_DELAY_TIME = 500;
    private static long lastClickTime;

    public static boolean isFastClick() {
        boolean flag = false;
        long curClickTime = System.currentTimeMillis();
        if ((curClickTime - lastClickTime) >= MIN_CLICK_DELAY_TIME) {
            flag = true;
        }
        lastClickTime = curClickTime;
        return flag;
    }

    /**
     * 获取版本名称
     *
     * @return 当前应用的版本名称
     */
    public static String getVersionName() {
        try {
            PackageManager manager = MyApplication.context.getPackageManager();
            PackageInfo info = manager.getPackageInfo(MyApplication.context.getPackageName(), 0);
            String version = info.versionName;
            return version;
        } catch (Exception e) {
            e.printStackTrace();
            return "0.00";
        }
    }

    public static Uri getCutPicPath(Context context) {
        File tfile = new File(Constant.PIC_PATH);
        if (!tfile.exists()) {
            try {
                tfile.mkdirs();
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {

        }

        return Uri.fromFile(new File(Constant.PIC_PATH + System.currentTimeMillis() + ".jpg"));
    }


    public static Uri file2Uri(Context ctx) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            File file = new File(Environment.getExternalStorageDirectory(), "/temp/" + System.currentTimeMillis() + ".jpg");
            return FileProvider.getUriForFile(ctx, "com.superservice.lya.fileprovider", file);
        } else {
            return Uri.fromFile(new File(Constant.PIC_PATH + System.currentTimeMillis() + ".jpg"));
        }
    }

    public static void goToPersonInfo(Context mContext, String user_id) {
        Intent intent = new Intent(mContext, PersonInfoActivity.class);
        intent.putExtra("userId", "" + user_id);
        mContext.startActivity(intent);
    }

    public static Uri getCutPicPath() {
        File tfile = new File(Constant.PIC_PATH);
        if (!tfile.exists()) {
            try {
                tfile.mkdirs();
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {

        }

        return Uri.fromFile(new File(Constant.PIC_PATH + System.currentTimeMillis() + ".jpg"));
    }

    public static String getPicRootPath() {
        File tfile = new File(Constant.PIC_PATH_SAVE);
        if (!tfile.exists()) {
            try {
                tfile.mkdirs();
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {

        }

        return Constant.PIC_PATH_SAVE;
    }

    public static CompressConfig takePhotoCompress() {

        //设置压缩参数
        //CompressConfig compressConfig =
        //takePhoto.onEnableCompress(compressConfig, true);
        //设置为需要压缩
        return new CompressConfig.Builder().setMaxSize(100 * 1024).create();
    }

    public static CropOptions getCutPicCropOptions() {
//        boolean withWonCrop = true;
        CropOptions.Builder builder = new CropOptions.Builder();
        builder.setWithOwnCrop(false);
        return builder.create();
    }

    public static CropOptions getCutPicCropOptions2() {
        boolean withWonCrop = true;
        CropOptions.Builder builder = new CropOptions.Builder();
        builder.setWithOwnCrop(withWonCrop);
        return builder.create();
    }

    public static CropOptions getSquareCutPicCropOptions() {
        boolean withWonCrop = true;
        CropOptions.Builder builder = new CropOptions.Builder();
        builder.setAspectX(4).setAspectY(4);
        builder.setWithOwnCrop(withWonCrop);
        return builder.create();
    }

    public static String getHtmlData(String bodyHTML) {
        String head = "<head>" +
                "<meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0, user-scalable=no\"> " +
                "<style>img{max-width: 100%; width:auto; height:auto;}</style>" +
                "</head>";
        return "<html>" + head + "<body>" + bodyHTML + "</body></html>";
    }

    public static void goToActivity(String type, String id, Context context) {

        //        1贴子,2问答,3物品,4招聘,5培训,6活动,7小视频',
        Intent intent;
        switch (type) {
            case "1":
                intent = new Intent(context, TzDetailActivity.class);

                intent.putExtra("wdListDataBean", id);

                context.startActivity(intent);
                break;
            case "2":
                intent = new Intent(context, ToothDetailsActivity.class);
                intent.putExtra("wdListDataBean", id);
                context.startActivity(intent);

                break;
            case "3":

                intent = new Intent(context, GoodsDetailActivity.class);
                intent.putExtra("GoodsDataBean", id + "");
                context.startActivity(intent);

                break;
            case "4":

                intent = new Intent(context, InviteDetailActivity.class);
                intent.putExtra("recruitId", id);
                context.startActivity(intent);

                break;
            case "5":

                intent = new Intent(context, TrainApplyDetailActivity.class);
                intent.putExtra("trainId", id);
                context.startActivity(intent);

                break;
            case "6":
                intent = new Intent(context, FancyActivityDetailActivity.class);
                intent.putExtra("trainId", id);
                context.startActivity(intent);

                break;
            case "7":

                intent = new Intent(context, LifeVideoDetailActivity.class);

                intent.putExtra(VideoDetailActivity.VEDIO_KEY, id);

                context.startActivity(intent);

                break;
        }


    }

    public static void goMsgToActivity(String type, String id, Context context) {

        //       1问答, 2贴子,3小视频',4物品,
        Intent intent;
        switch (type) {
            case "1":
                intent = new Intent(context, ToothDetailsActivity.class);
                intent.putExtra("wdListDataBean", id);
                context.startActivity(intent);

                break;
            case "2":

                intent = new Intent(context, TzDetailActivity.class);

                intent.putExtra("wdListDataBean", id);

                context.startActivity(intent);


                break;
            case "3":

                intent = new Intent(context, LifeVideoDetailActivity.class);

                intent.putExtra(VideoDetailActivity.VEDIO_KEY, id);

                context.startActivity(intent);

                break;
            case "4":
                intent = new Intent(context, GoodsDetailActivity.class);
                intent.putExtra("GoodsDataBean", id + "");
                context.startActivity(intent);

                break;
        }


    }

    public static File getLiZiPicFile() {
        File file = new File(Environment.getExternalStorageDirectory(), "/LinYa/" + System.currentTimeMillis() + ".jpg");
        if (!file.getParentFile().exists()) {
            file.getParentFile().mkdirs();
        }
        return file;
    }

    /**
     * 大陆手机号码11位数，匹配格式：前三位固定格式+后8位任意数
     * 此方法中前三位格式有：
     * 13+任意数
     * 15+除4的任意数
     * 18+除1和4的任意数
     * 17+除9的任意数
     * 147
     */
    public static boolean isChinaPhoneLegal(String str) {

        if (TextUtils.isEmpty(str)) {
            return false;
        }
        String regExp = "^((13[0-9])|(15[0-9])|(18[0-9])|(17[0-9])|(147[0-9]))\\d{8}$";
        Pattern p = Pattern.compile(regExp);
        Matcher m = p.matcher(str);
        return m.matches();
    }

    public static int getScreenSizeOfDevice() {
        DisplayMetrics dm = MyApplication.context.getResources().getDisplayMetrics();
        int width = dm.widthPixels;
        int height = dm.heightPixels;

        double x = Math.pow(width, 2);
        double y = Math.pow(height, 2);
        double diagonal = Math.sqrt(x + y);

        int dens = dm.densityDpi;
        double screenInches = diagonal / (double) dens;

        return (int) screenInches;
    }

    public static int getScreenWidth(Context context) {
        DisplayMetrics dm = context.getResources().getDisplayMetrics();
        return dm.widthPixels;
    }

    public static int getScreenHeight(Context context) {
        DisplayMetrics dm = context.getResources().getDisplayMetrics();
        return dm.heightPixels;
    }

    public static int dip2pix(Context context, int dip) {
        DisplayMetrics dm = context.getResources().getDisplayMetrics();
        return (int) (dm.density * (float) dip);
    }


    /**
     * 检查手机上是否安装了指定的软件
     *
     * @param context
     * @param packageName：应用包名
     * @return
     */
    public static boolean isAvilible(Context context, String packageName) {
        // 获取packagemanager
        final PackageManager packageManager = context.getPackageManager();
        // 获取所有已安装程序的包信息
        List<PackageInfo> packageInfos = packageManager.getInstalledPackages(0);
        // 用于存储所有已安装程序的包名
        List<String> packageNames = new ArrayList<String>();
        // 从pinfo中将包名字逐一取出，压入pName list中
        if (packageInfos != null) {
            for (int i = 0; i < packageInfos.size(); i++) {
                String packName = packageInfos.get(i).packageName;
                packageNames.add(packName);
            }
        }
        // 判断packageNames中是否有目标程序的包名，有TRUE，没有FALSE
        return packageNames.contains(packageName);
    }


    public static String MD5(String plaintext) {
        char hexDigits[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
                'a', 'b', 'c', 'd', 'e', 'f'};
        try {
            byte[] btInput = plaintext.getBytes();
            // 获得MD5摘要算法的 MessageDigest 对象
            MessageDigest mdInst = MessageDigest.getInstance("MD5");
            // 使用指定的字节更新摘要
            mdInst.update(btInput);
            // 获得密文
            byte[] md = mdInst.digest();
            // 把密文转换成十六进制的字符串形式
            int j = md.length;
            char str[] = new char[j * 2];
            int k = 0;
            for (int i = 0; i < j; i++) {
                byte byte0 = md[i];
                str[k++] = hexDigits[byte0 >>> 4 & 0xf];
                str[k++] = hexDigits[byte0 & 0xf];
            }
            return new String(str);
        } catch (Exception e) {
            return null;
        }
    }


    public static String getTime(Date date) {//可根据需要自行截取数据显示
        Log.d("getTime()", "choice date millis: " + date.getTime());
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        return format.format(date);
    }

    /**
     * "yyyy-MM-dd HH:mm:ss"
     *
     * @param date
     * @param timeType
     * @return
     */
    public static String getTime(Date date, String timeType) {//可根据需要自行截取数据显示
        Log.d("getTime()", "choice date millis: " + date.getTime());
        SimpleDateFormat format = new SimpleDateFormat(timeType);
        return format.format(date);
    }

    /**
     * 将图片转换成Base64编码的字符串
     *
     * @param path
     * @return base64编码的字符串
     */
    public static String imageToBase64(String path) {
        if (TextUtils.isEmpty(path)) {
            return null;
        }
        InputStream is = null;
        byte[] data = null;
        String result = null;
        try {
            is = new FileInputStream(path);
            //创建一个字符流大小的数组。
            data = new byte[is.available()];
            //写入数组
            is.read(data);
            //用默认的编码格式进行编码
            result = Base64.encodeToString(data, Base64.DEFAULT);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (null != is) {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

        }
        return result;
    }


    public static void loginRongYun() {
        HttpMehtod.getInstance().getRongToken(new IdeaObserver<BaseDataBean<RongYunDataBean>>() {

            @Override
            public void onSuccess(final BaseDataBean<RongYunDataBean> rongYunDataBeanBaseDataBean) {

                if (!TextUtils.isEmpty(rongYunDataBeanBaseDataBean.getData().getToken())) {
                    RongIM.connect(rongYunDataBeanBaseDataBean.getData().getToken(), new RongIMClient.ConnectCallback() {
                        @Override
                        public void onTokenIncorrect() {

                        }

                        @Override
                        public void onSuccess(String userid) {

                            MyApplication.ryIsLogin = true;

                            if ((!TextUtils.isEmpty(rongYunDataBeanBaseDataBean.getData().getNick_name())) && (!TextUtils.isEmpty(rongYunDataBeanBaseDataBean.getData().getImgsrc()))) {
                                RongIM.getInstance().setCurrentUserInfo(new UserInfo(userid, rongYunDataBeanBaseDataBean.getData().getNick_name(), Uri.parse(rongYunDataBeanBaseDataBean.getData().getImgsrc())));
                            } else {
                                RongIM.getInstance().setCurrentUserInfo(new UserInfo(userid, "", null));
                            }

                            /**
                             * 设置消息体内是否携带用户信息。
                             *
                             * @param state 是否携带用户信息，true 携带，false 不携带。
                             */
                            RongIM.getInstance().setMessageAttachedUserInfo(true);
                        }

                        @Override
                        public void onError(RongIMClient.ErrorCode errorCode) {

                        }
                    });
                }

            }

            @Override
            public void onFail(int errorCode) {
                MyApplication.ryIsLogin = false;
            }
        });

    }

    public static void savePosition() {
        Map map = new HashMap();

        LogUtil.MyLog("savePosition", MyApplication.longitude + "===savePosition====" + MyApplication.latitude);

        DecimalFormat df = new DecimalFormat("#0.00000");

        map.put("lng", df.format(MyApplication.longitude));

        map.put("lat", df.format(MyApplication.latitude));


        HttpMehtod.getInstance().savePosition(map, new IdeaObserver<BaseDataBean>() {


            @Override
            public void onSuccess(BaseDataBean baseDataBean) {

            }

            @Override
            public void onFail(int errorCode) {

            }
        });

    }

    public static String htmlReplace(String str) {
        str = str.replace("&ldquo;", "“");
        str = str.replace("&rdquo;", "”");
        str = str.replace("&nbsp;", " ");
        str = str.replace("&", "&amp;");
        str = str.replace("&#39;", "'");
        str = str.replace("&rsquo;", "’");
        str = str.replace("&mdash;", "—");
        str = str.replace("&ndash;", "–");
        return str;
    }


    /**
     * 通过imageWidth 的宽度，自动适应高度
     * * @param simpleDraweeView view
     * * @param imagePath  Uri
     * * @param imageWidth width
     */
    public static void setControllerListener(final SimpleDraweeView simpleDraweeView, String imagePath, final float imageWidth) {
        final ViewGroup.LayoutParams layoutParams = simpleDraweeView.getLayoutParams();
        ControllerListener controllerListener = new BaseControllerListener<ImageInfo>() {
            @Override
            public void onFinalImageSet(String id, @Nullable ImageInfo imageInfo, @Nullable Animatable anim) {
                if (imageInfo == null) {
                    return;
                }
                int height = imageInfo.getHeight();
                int width = imageInfo.getWidth();
                layoutParams.width = (int) imageWidth;
                layoutParams.height = (int) ((float) (imageWidth * height) / (float) width);
                simpleDraweeView.setLayoutParams(layoutParams);
            }

            @Override
            public void onIntermediateImageSet(String id, @Nullable ImageInfo imageInfo) {
                Log.d("TAG", "Intermediate image received");
            }

            @Override
            public void onFailure(String id, Throwable throwable) {
                throwable.printStackTrace();
            }
        };
        DraweeController controller = Fresco.newDraweeControllerBuilder().setControllerListener(controllerListener).setUri(Uri.parse(imagePath)).build();
        simpleDraweeView.setController(controller);
    }


    /**
     * RecyclerView 移动到当前位置，
     *
     * @param manager       设置RecyclerView对应的manager
     * @param mRecyclerView 当前的RecyclerView
     * @param n             要跳转的位置
     */
    public static void MoveToPosition(LinearLayoutManager manager, RecyclerView mRecyclerView, int n) {
        int firstItem = manager.findFirstVisibleItemPosition();
        int lastItem = manager.findLastVisibleItemPosition();
        if (n <= firstItem) {
            mRecyclerView.scrollToPosition(n);
        } else if (n <= lastItem) {
            int top = mRecyclerView.getChildAt(n - firstItem).getTop();
            mRecyclerView.scrollBy(0, top);
        } else {
            mRecyclerView.scrollToPosition(n);
        }
    }

}
